package com.solo.jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        // 汉字编码设置
        request.setCharacterEncoding("utf-8");
        // 得到用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = null;
        conn = DBUtil.getConn();
        try {
            conn.setAutoCommit(false);
            pst = conn.prepareStatement("select * from sys_user where username=? and password=?");
            pst.setString(1, username);
            pst.setString(2, password);
            rs = pst.executeQuery();
            if (rs.next()) {
                Long id = rs.getLong("id");
                String username1 = rs.getString("username");
                String password1 = rs.getString("password");
                user = new User(id, username1, password1);
            }
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConn(rs, pst, conn);
        }
        // 存在则进入主界面
        if (user != null) {
            // request.getSession().setAttribute("user", user);
            request.getRequestDispatcher("/main.jsp").forward(request, response);
        }else {
            response.sendRedirect(request.getContextPath() + "/failure.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
